package com.jy.modules.cims.loan;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.open.api.JieYueApiHelper;
import com.jy.modules.cims.common.open.api.dto.EntryParameter;
import com.jy.modules.cims.common.open.api.dto.ResponseContent;
import com.jy.modules.cims.common.open.api.enums.EntryResponseEnum;
import com.jy.modules.cims.component.sysAssist.JieYueApiAssist;
import com.jy.modules.cims.data.interact.tbj.loan.request.RequestAuditResultDTO;
import com.jy.modules.cims.data.interact.tbj.loan.request.RequestLoanResultDTO;
import com.jy.modules.cims.data.interact.tbj.loan.request.RequestProdInfoDTO;
import com.jy.modules.cims.data.interact.tbj.loan.request.RequestProdLoanDTO;
import com.jy.modules.cims.data.interact.tbj.loan.request.RequestRaisePlanDTO;
import com.jy.modules.cims.data.interact.tbj.loan.request.RequestTradeDebtorDTO;
import com.jy.modules.cims.data.interact.tbj.loan.response.ResponseDataDTO;
import com.jy.modules.cims.data.interact.tbj.loan.response.ResponseDataEnum;
import com.jy.modules.cims.loan.service.TBJLoanService;


/**
 * @classname LoanController
 * @description 定义对外围系统发布的贷款服务的总控制层
 * @author shengzhoutao
 * @date 2015-09-07
 */
@Controller
@RequestMapping(value = "/api/loan")
public class LoanController {
	private static Logger logger = LoggerFactory.getLogger(LoanController.class);
	private String METHOD_TBJ_LOAN_RAISE_PLAN = "tbj.loan.raise.plan";
	private String METHOD_TBJ_LOAN_AUDIT_RESULT = "tbj.loan.audit.result";
	private String METHOD_TBJ_LOAN_LOAN_RESULT = "tbj.loan.loan.result";
	private String METHOD_TBJ_LOAN_PROD_LOAN = "tbj.loan.prod.loan";
	private String METHOD_TBJ_LOAN_TRADE_DEBTOR = "tbj.loan.trade.debtor";
	private String METHOD_TBJ_LOAN_LOAN_INFO = "tbj.loan.prod.info";

	@Autowired
	@Qualifier("com.jy.modules.cims.loan.service.TBJLoanService")
	private TBJLoanService tbjLoanService;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.sysAssist.JieYueApiAssist")
	private JieYueApiAssist jieYueApiAssist;
	
	/**
	 * @description 对铜板街提供的贷款服务处理
	 * @param request
	 *            request请求
	 * @param parameter
	 *            参数实体对象
	 * @return ResponseContent
	 * @author shengzhoutao
	 * @date 2015-09-07
	 */
	@RequestMapping(value = "/tongbanjie", method = RequestMethod.POST)
	@ResponseBody
	public ResponseContent tongbanjie(HttpServletRequest request, EntryParameter parameter) {
		logger.info("==============接受铜板街请求, 处理贷款服务==============");
		
		ResponseContent responseContent = null;
		
		// 没有收到参数
		if (null == parameter) {
			responseContent = new ResponseContent(EntryResponseEnum.FAILURE41009);
			logger.info("处理结果，返回响应：" + responseContent);
			return responseContent;
		}
		
		boolean success = validateEntryParameter(parameter, responseContent);
		if (!success) {
			responseContent = new ResponseContent(EntryResponseEnum.FAILURE41001);
			logger.info("处理结果，返回响应：" + responseContent);
			return responseContent;
		}

		JieYueApiHelper helper = jieYueApiAssist.getJieYueApiHelperByCooperorgCode(CimsConstant.TBJ_COOPERORG_CODE);
		ResponseDataDTO responseData = new ResponseDataDTO();
		responseContent = new ResponseContent(EntryResponseEnum.SUCESS21001);
		String method = parameter.getMethod();
		logger.info("请求服务方法：" + method);
		// 接收募集计划申请接口
		if (METHOD_TBJ_LOAN_RAISE_PLAN.equals(method)) {
			RequestRaisePlanDTO dto = helper.parseData(parameter, RequestRaisePlanDTO.class);
			String errorMessage = tbjLoanService.validate(dto);
			if (StringUtils.hasText(errorMessage)) {
				responseContent = new ResponseContent(EntryResponseEnum.FAILURE41003);
				responseContent.setMessage(responseContent.getMessage() + "[" + errorMessage + "]");
			} else {
				try {
					responseData = tbjLoanService.doRaisePlan(dto);
				} catch (Exception e) {
					logger.error("接收募集计划申请处理异常：", e);
					responseData = new ResponseDataDTO(dto.getPlanId(), ResponseDataEnum.FAILURE.getCode(), ResponseDataEnum.FAILURE.getMessage()
							+ "[接收募集计划申请处理异常  " + e.getMessage() + "]");
				}
			}
		}
		// 接收贷款审批结果接口
		else if (METHOD_TBJ_LOAN_AUDIT_RESULT.equals(method)) {
			RequestAuditResultDTO dto = helper.parseData(parameter, RequestAuditResultDTO.class);
			String errorMessage = tbjLoanService.validate(dto);
			if (StringUtils.hasText(errorMessage)) {
				responseContent = new ResponseContent(EntryResponseEnum.FAILURE41003);
				responseContent.setMessage(responseContent.getMessage() + "[" + errorMessage + "]");
			} else {
				try {
					responseData = tbjLoanService.doAuditResult(dto);
				} catch (Exception e) {
					logger.error("接收贷款审批结果处理异常：", e);
					responseData = new ResponseDataDTO(dto.getStreamId(), ResponseDataEnum.FAILURE.getCode(), ResponseDataEnum.FAILURE.getMessage()
							+ "[贷款审批结果处理异常  " + e.getMessage() + "]");
				}
			}
		}
		// 接收贷款放款结果接口
		else if (METHOD_TBJ_LOAN_LOAN_RESULT.equals(method)) {
			RequestLoanResultDTO dto = helper.parseData(parameter, RequestLoanResultDTO.class);
			String errorMessage = tbjLoanService.validate(dto);
			if (StringUtils.hasText(errorMessage)) {
				responseContent = new ResponseContent(EntryResponseEnum.FAILURE41003);
				responseContent.setMessage(responseContent.getMessage() + "[" + errorMessage + "]");
			} else {
				try {
					responseData = tbjLoanService.doLoanResult(dto);
				} catch (Exception e) {
					logger.error("接收贷款放款结果处理异常：", e);
					responseData = new ResponseDataDTO(dto.getStreamId(), ResponseDataEnum.FAILURE.getCode(), ResponseDataEnum.FAILURE.getMessage()
							+ "[贷款放款结果处理异常  " + e.getMessage() + "]");
				}
			}
		}
		// 接收产品相关的债权信息接口(该接口暂时不用)
		else if (METHOD_TBJ_LOAN_PROD_LOAN.equals(method)) {
			RequestProdLoanDTO dto = helper.parseData(parameter, RequestProdLoanDTO.class);
			String errorMessage = tbjLoanService.validate(dto);
			if (StringUtils.hasText(errorMessage)) {
				responseContent = new ResponseContent(EntryResponseEnum.FAILURE41003);
				responseContent.setMessage(responseContent.getMessage() + "[" + errorMessage + "]");
			} else {
				try {
					responseData = tbjLoanService.doProdLoan(dto);
				} catch (Exception e) {
					logger.error("接收产品相关的债权信息异常：", e);
					responseData = new ResponseDataDTO(dto.getProductId(), ResponseDataEnum.FAILURE.getCode(), ResponseDataEnum.FAILURE.getMessage()
							+ "[接收产品相关的债权信息异常  " + e.getMessage() + "]");
				}
			}
		}
		// 接收债权匹配信息(该接口暂时不用)
		else if (METHOD_TBJ_LOAN_TRADE_DEBTOR.equals(method)) {
			RequestTradeDebtorDTO dto = helper.parseData(parameter, RequestTradeDebtorDTO.class);
			String errorMessage = tbjLoanService.validate(dto);
			if (StringUtils.hasText(errorMessage)) {
				responseContent = new ResponseContent(EntryResponseEnum.FAILURE41003);
				responseContent.setMessage(responseContent.getMessage() + "[" + errorMessage + "]");
			} else {
				try {
					responseData = tbjLoanService.doTradeDebtor(dto);
				} catch (Exception e) {
					logger.error("接收债权匹配信息异常：", e);
					responseData = new ResponseDataDTO(dto.getProductId(), ResponseDataEnum.FAILURE.getCode(), ResponseDataEnum.FAILURE.getMessage()
							+ "[接收债权匹配信息异常  " + e.getMessage() + "]");
				}
			}
		}
		//接受铜板街贷款产品上架信息(该接口暂时不用)
		else if (METHOD_TBJ_LOAN_LOAN_INFO.equals(method)) {
			RequestProdInfoDTO dto = helper.parseData(parameter, RequestProdInfoDTO.class);
			String errorMessage = tbjLoanService.validate(dto);
			if (StringUtils.hasText(errorMessage)) {
				responseContent = new ResponseContent(EntryResponseEnum.FAILURE41003);
				responseContent.setMessage(responseContent.getMessage() + "[" + errorMessage + "]");
			} else {
				try {
					responseData = tbjLoanService.doProdInfo(dto);
				} catch (Exception e) {
					logger.error("接收产品上架信息异常 ：", e);
					responseData = new ResponseDataDTO(dto.getProductId(), ResponseDataEnum.FAILURE.getCode(), ResponseDataEnum.FAILURE.getMessage()
							+ "[接收产品上架信息异常  " + e.getMessage() + "]");
				}
			}
		}
		// API接口名称取值不正确
		else {
			responseContent = new ResponseContent(EntryResponseEnum.FAILURE41003);
			responseContent.setMessage(java.text.MessageFormat.format("API接口名称[{0}]取值不正确。", new Object[] { method }));
		}

		responseContent.setMethod(parameter.getMethod());
		responseContent.setSign(parameter.getSign());
		helper.assembleResponse(responseContent, responseData);

		logger.info("处理结果，返回响应：" + responseContent);

		return responseContent;
	}

	/**
	 * 
	 * @param parameter
	 * @param responseContent
	 * @return
	 */
	private boolean validateEntryParameter(final EntryParameter parameter, ResponseContent responseContent) {
		
		String timestamp = parameter.getTimestamp();
		logger.info("铜板街请求时间：" + timestamp);

		JieYueApiHelper helper = jieYueApiAssist.getJieYueApiHelperByCooperorgCode("TBJ");
		// 验证签名不通过
		if (!helper.checkSign(parameter)) {
			return false;
		}
		return true;
	}
}
